<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { createQA, updateQA } from '@/api/qa'
import { getArticleList } from '@/api/article'
import type { ArticleQA, Article } from '@/api/types'
import { SceneType } from '@/api/types'
import { handleError } from '@/utils/error-handler'

const props = defineProps<{
  visible: boolean
  data?: Partial<ArticleQA>
}>()

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}>()

// 表单数据
const formRef = ref()
const form = ref<Partial<ArticleQA>>({
  articleId: undefined,
  question: '',
  answer: '',
  sceneType: undefined
})

// 表单校验规则
const rules = {
  question: [{ required: true, message: '请输入问题', trigger: 'blur' }],
  answer: [{ required: true, message: '请输入答案', trigger: 'blur' }],
  sceneType: [{ required: true, message: '请选择场景类型', trigger: 'change' }]
}

// 文章选择相关
const articles = ref<Article[]>([])
const articleLoading = ref(false)

// 加载状态
const loading = ref(false)

// 监听弹窗显示状态
watch(() => props.visible, (val) => {
  console.log('Dialog visible changed:', val)
  if (val && props.data) {
    console.log('Dialog data:', props.data)
    form.value = { ...props.data }
  } else {
    form.value = {
      articleId: undefined,
      question: '',
      answer: '',
      sceneType: undefined
    }
  }
})

// 搜索文章
async function loadArticles(query: string) {
  if (!query) return
  
  articleLoading.value = true
  try {
    const res = await getArticleList({
      keyword: query,
      pageSize: 10
    })
    articles.value = res.data.data.records
  } catch (error) {
    handleError(error)
  } finally {
    articleLoading.value = false
  }
}

// 关闭弹窗
function handleClose() {
  emit('update:visible', false)
  formRef.value?.resetFields()
}

// 提交表单
async function handleSubmit() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    if (form.value.id) {
      // 编辑模式
      await updateQA(form.value.id, form.value)
      ElMessage.success('更新成功')
    } else {
      // 新增模式
      await createQA(form.value)
      ElMessage.success('创建成功')
    }
    
    emit('success')
    handleClose()
  } catch (error) {
    if (error.message) {
      handleError(error)
    }
  } finally {
    loading.value = false
  }
}

// 确保组件名称定义
defineOptions({
  name: 'QADialog'
})
</script>

<template>
  <el-dialog
    :title="data?.id ? '编辑问答' : '新增问答'"
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    width="800px"
    @close="handleClose"
    class="qa-dialog"
  >
    <div style="display: none;">
      Visible: {{ visible }}
      Data: {{ data }}
    </div>
    
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="qa-form"
    >
      <el-form-item label="关联文章">
        <el-select
          v-model="form.articleId"
          filterable
          remote
          :remote-method="loadArticles"
          :loading="articleLoading"
          placeholder="请输入文章标题搜索"
          class="article-select"
          clearable
        >
          <el-option
            v-for="item in articles"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="问题" prop="question">
        <el-input
          v-model="form.question"
          type="textarea"
          :rows="3"
          placeholder="请输入问题"
        />
      </el-form-item>

      <el-form-item label="答案" prop="answer">
        <el-input
          v-model="form.answer"
          type="textarea"
          :rows="3"
          placeholder="请输入答案"
        />
      </el-form-item>

      <el-form-item label="场景类型" prop="sceneType">
        <el-select v-model="form.sceneType" placeholder="请选择场景类型">
          <el-option label="热恋中" :value="SceneType.IN_LOVE" />
          <el-option label="追求中" :value="SceneType.PURSUING" />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.qa-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
  }

  .qa-form {
    padding: 30px;

    .article-select {
      width: 100%;
    }

    :deep(.el-form-item) {
      margin-bottom: 24px;
    }

    :deep(.el-textarea__inner) {
      font-family: inherit;
      padding: 12px;
      min-height: 100px;
    }

    :deep(.el-select) {
      width: 100%;
    }
  }

  :deep(.el-dialog__footer) {
    padding: 20px 30px;
    border-top: 1px solid #dcdfe6;
  }
}
</style> 